<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/21 23:42
 */

namespace module\ai\library\channel\completion;

use module\ai\library\channel\abstract\Completion;

class XunfeiCompletion extends Completion
{
    protected function rawToData(): void
    {
        $raw = $this->rawData;
        if (!empty($raw['type'])) {
            list($message, $clear) = match ($raw['type']) {
                'content_filter' => ['您输入的信息存在违规内容，请重新调整输入内容。', true],
                'invalid_request_error' => ['对不起，输入的内容过多，我暂时回答你的问题。', false],
                default => [$raw['message'], true],
            };
            $this->error($message, $raw['type'], $clear);
        } elseif (isset($raw['choices'])) {
            $message = $this->stream ? $raw['choices'][0]['delta'] : $raw['choices'][0]['message'];
            $this->data['message'] = $message;
            $this->data['status'] = $this->stream ? (empty($raw['finish_reason']) ? 'receiving' : 'finish') : 'finish';
            $this->data['index'] = $raw['choices'][0]['index'] ?? 0;
            if (isset($raw['usage'])) {
                $this->data['tokens'] = [
                    'send_tokens'    => $raw['usage']['prompt_tokens'] ?? 0,
                    'receive_tokens' => $raw['usage']['completion_tokens'] ?? 0,
                    'total_tokens'   => $raw['usage']['total_tokens'] ?? 0,
                ];
            }
        }
    }

}